package com.edu.hre.common.utils;

import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.edu.hre.db.pojo.HreConfig;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.struts.action.pim.EmployeeListAction;

public class DynamicConfig {
	
	private static final Logger logger = Logger.getLogger(DynamicConfig.class);
	private static HashMap<String, String> map = new HashMap<String, String>();
	private static final int limit = 1000;
	
	public static final String PAGE_SIZE = "page_size";
	public static final String MAX_LEAVE_DAYS = "max_leave_days";
	public static final String START_TIME = "start_time";
	public static final String END_TIME = "end_time";
	
	public static void addConfig(String name, String value){
		if(getSize() < limit){
			map.put(name, value);
		}
	}
	
	public static void addConfig(HreConfig dynamicConfig){
		if(dynamicConfig != null && StringUtils.isNotBlank(dynamicConfig.getKey1())){
			addConfig(dynamicConfig.getKey1(), dynamicConfig.getValue());
		}
	}
	
	public static String getConfig(String name){
		return (String) map.get(name);
	}
	
	public static int getSize(){
		return map.size();
	}

	public synchronized static void loadDynamicConfig(){
		try {
			BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
			List<HreConfig> listDynamicConfig = baseService.getPojos(null, -1, null, null, null, 1000, 0, HreConfig.class);
			for(int i = 0; listDynamicConfig != null && i < listDynamicConfig.size(); i ++){
				HreConfig dynamicConfig = (HreConfig) listDynamicConfig.get(i);
				if(StringUtils.isNotBlank(dynamicConfig.getKey1())){
					addConfig(dynamicConfig);
				}
			}  
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
}
